# coding=utf-8
'''
Created on 2012-8-26

@author: quanwei
'''
from core import Analyzer
import MySQLdb 
import threading
from dzdp import DbHelper
#基类
localData = threading.local()
class BaseAnalyzer(Analyzer.Analyzer):
    #db对象
    def getDb(self):
        if localData.__dict__.get("db") == None:
            localData.__dict__["db"] = DbHelper.DbHelper()
        return localData.__dict__["db"]
    #任务是否存在
    def existsTask(self,task):
        db = self.getDb()
        tid = db.fetchOne("select id from dzdp.Task where url='%s'" %(task.url))
        if tid == None:
            return False
        else:
            return True
    #商铺是否存在
    def existsShop(self,shop):
        db = self.getDb()
        sid = db.fetchOne("select id from dzdp.Shop where url='%s'" %(shop['url']))
        if sid == None:
            return False
        else:
            return True
    #完成任务
    def complateTask(self,task,status=1):
        db = self.getDb()
        sql = "update dzdp.Task set status=%s where id=%s" % (status,task.id)
        db.execute(sql)
    #添加新任务
    def saveTask(self,newTask):
        db = self.getDb()
        paramCategory = MySQLdb.escape_string(newTask.data['category'])
        paramUrl = MySQLdb.escape_string(newTask.url)
        paramCity = MySQLdb.escape_string(newTask.data['city'])
        sql = "insert into dzdp.Task set category='%s',city='%s',url='%s'" % (paramCategory,paramCity,paramUrl)
        db.execute(sql)
        newTask.id = db.lastInsertId()
    #添加新商铺
    def saveShop(self,shop):
        db = self.getDb()
        paramName = MySQLdb.escape_string(shop['name'])
        paramCategory = MySQLdb.escape_string(shop['category'])
        paramPrice = shop['price']
        paramTags = MySQLdb.escape_string(",".join(shop['tags']))
        paramAddr = MySQLdb.escape_string(shop['addr'])
        paramCity = MySQLdb.escape_string(shop['city'])
        paramUrl = MySQLdb.escape_string(shop['url'])    
        sql = "insert into dzdp.Shop set name='%s',category='%s',price=%s,tags='%s',addr='%s',city='%s',url='%s'" % (paramName,paramCategory,paramPrice,paramTags,paramAddr,paramCity,paramUrl)
        db.execute(sql)
            